package com.shixu.framework.plugins.weixin.service;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.shixu.framework.plugins.weixin.util.HttpKit;

/**
 * 菜单
 */
public class MenuService {

    /**
     * 创建菜单
     * @throws IOException 
     * @throws NoSuchProviderException 
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
	public boolean createMenu(String accessToken,String params) throws InterruptedException, ExecutionException, IOException {
        String jsonStr = HttpKit.post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken, params);
        Map<String, Object> map = JSON.parseObject(jsonStr,Map.class);
        return "0".equals(map.get("errcode").toString());
    }
    
    /**
     * 查询菜单
     * @throws IOException 
     * @throws NoSuchProviderException 
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
    public JSONObject getMenuInfo(String accessToken) throws InterruptedException, ExecutionException, NoSuchAlgorithmException, KeyManagementException, IOException, NoSuchProviderException {
        String jsonStr = HttpKit.get("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);
        if(StringUtils.isNotEmpty(jsonStr)){
    		return JSONObject.fromObject(jsonStr);
    	}
        return null;
    }
    
    /**
     * 删除自定义菜单
     * @throws IOException 
     * @throws NoSuchProviderException 
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
    public boolean deleteMenu(String accessToken) throws InterruptedException, ExecutionException, NoSuchAlgorithmException, KeyManagementException, IOException, NoSuchProviderException {
        String jsonStr = HttpKit.get("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);
        Map<String, Object> map = JSON.parseObject(jsonStr, Map.class);
        return "0".equals(map.get("errcode").toString());
    }
    
    
    
    /**
	 * 测试
	 * @param args
	 * @throws Exception 
	 * @throws IOException
	 * @throws InterruptedException 
	 * @throws ExecutionException 
	 */
	public static void main(String[] args) throws Exception{
		//实例化操作类
		MenuService menu = new MenuService();		
		//定义返回值
		String result = null;
		
		String access_token = "fWbIL3Gy1pPkF9aNIXWzV9CreOH9wxV8GELTchOBvDvFv2jFYB9RyKmMr9phXYSYYctufMK6n3IahwRKVC7h0FjZqlKxH0A_nEo8HI-6nSU";
		String openid = "o9QgNuDF7-3lY4nH1yuLRF-jRhvg";
		
		/* 查询菜单 */
		result = menu.getMenuInfo(access_token).toString();
		System.out.println("查询菜单----"+result);
		
	    
	  
	}  
}
